package com.davidlife.javase.netsocket.uploadfiles;

import java.io.*;
import java.net.Socket;

public class TcpUploadClient {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("127.0.0.1", 8888);
        OutputStream os = s.getOutputStream();

        String path = "D:\\workspace\\IdeaProjects\\javase-demo\\knowledge-javaSE-demo\\notes-images\\ASCII码表.png";
        System.out.println("上传文件：" + path);

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
        BufferedOutputStream bos = new BufferedOutputStream(os);
        byte[] b = new byte[1024 * 8];
        int len;
        while ((len = bis.read()) != -1) {
            bos.write(b, 0, len);
        }
        bos.flush();
        // 关闭输出流,通知服务端,写出数据完毕。他会输出一个结束标记，is.read() 读到这个结束标记就会返回 -1 。
        s.shutdownOutput();  //这里注意：一定要加上这句话，否则服务端读不到结束标记，就会一直在那里等着读。

        InputStream is = s.getInputStream();
        byte[] rep = new byte[1024];
        int l;
        if ((l = is.read(rep)) != -1) {
            System.out.println("服务端的响应为：" + new String(rep, 0, l));
        }
        is.close();

        bos.close();
        bis.close();
        s.close();
    }
}
